var Login = {
    verifyAwaitTime: 0,
    viewList: [
        '.codeAndPasswordLogin',
        '.registerAccount',
        '.forgetPassword',
        '.resetPassword',
        '.agreement',
        '.bindPhone',
        '.wxCode',
        '.manualSendCode'
    ],
    viewHistory: ['.codeAndPasswordLogin'],
    countDownInterval: null,

    token: '',//用户名密码登录token
    code: '',//微信code
    init: function () {
        window['cr'] = {
            receiveMessage: function (e) {
                var msg = JSON.parse(e);
                if (msg.event === 406) {
                    zz_send(JSON.stringify({event: 404}));
                }
            }
        };
        document.onkeydown = function (e) {
            if (e.keyCode == 13) {
                var view = Login.viewHistory[Login.viewHistory.length - 1];
                if (view === '.codeAndPasswordLogin') {
                    if ($('.tabsItem.activated').attr('type') === 'code') {
                        $('#codeLoginBtn').trigger('click');
                    } else if ($('.tabsItem.activated').attr('type') === 'password') {
                        $('#passwordLoginBtn').trigger('click');
                    }
                }
                if (view === '.registerAccount') {
                    $('#registerBtn').trigger('click');
                }
                if (view === '.forgetPassword') {
                    $('#forgetPasswordNextBtn').trigger('click');
                }
                if (view === '.resetPassword') {
                    $('#savePasswordBtn').trigger('click');
                }
                if (view === '.bindPhone') {
                    $('#bindPhoneBtn').trigger('click');
                }
            }
        };
        try {
            zz_send(JSON.stringify({event: 405, title: '登录注册'}));
        } catch (e) {

        }
        window._pcReady = function () {
            zz_send(JSON.stringify({event: 405, title: '登录注册'}));
        };

        // 输入时清除输入框异常状态
        $('.longInput,.shortInput').on('input', function () {
            $(this).removeClass('inputError');
        });
        // 返回按钮点击
        $('.backBtn').click(function () {
            Login.closeView();
        });
        Login.initCodeAndPasswordLogin();
        Login.initRegister();
        Login.initForgetPassword();
        Login.initResetPassword();
        Login.initBindPhone();
        Login.initManualSendCode();
        Login.initImgVerifyCode();
    },
    // 显示视图并添加到历史
    showView: function (selector) {
        for (var i = 0; i < Login.viewList.length; i++) {
            $(Login.viewList[i]).hide();
        }
        $(selector).show();
        Login.viewHistory.push(selector);
        $('.longInput,.shortInput').removeClass('inputError');
    },
    // 关闭视图并从历史中移除
    closeView: function () {
        if (Login.viewHistory.length > 1) {
            $(Login.viewHistory.pop()).hide();
            $(Login.viewHistory[Login.viewHistory.length - 1]).show();
        } else {
            Login.viewHistory = ['.codeAndPasswordLogin'];
            $('.codeAndPasswordLogin').show();
        }
    },
    // 清除视图并清除所有输入框值
    clearView: function () {
        var inputList = $('input');
        for (var i = 0; i < inputList.length; i++) {
            $(inputList[i]).val('');
        }
        for (var i = 0; i < Login.viewList.length; i++) {
            $(Login.viewList[i]).hide();
        }
        Login.viewHistory = ['.codeAndPasswordLogin'];
        $('.codeAndPasswordLogin').show();
        Login.clearCountDown();
    },
    // 初始化登录视图
    initCodeAndPasswordLogin: function () {
        // 标签页点击
        $('.tabsItem').click(function () {
            if ($(this).attr('type') === 'code') {
                $('.passwordContent').hide();
                $('.codeLoginContent').show();
            } else if ($(this).attr('type') === 'password') {
                $('.codeLoginContent').hide();
                $('.passwordContent').show();
            }
            $('.tabsItem').removeClass('activated');
            $(this).addClass('activated');
            $('.longInput,.shortInput').removeClass('inputError');
        });
        // 发送验证码点击
        $('.getVerifyCode').click(function () {
            if (Login.verifyAwaitTime === 0 & Login.phoneVerify($(this).attr('inputSelector'))) {
                // 0:注册短信,1:手机号登录短信,2:微信登录绑定手机号短信,3:找回密码短信,4:用户名密码登录绑定手机号短信
                LoginAjax.sendVerifyCode($($(this).attr('inputSelector')).val(), $(this).attr('token'), $(this).attr('code'), $(this).attr('source'), function (res) {
                    Login.showToast('验证码发送成功', 'success');
                    Login.countDown();
                }, function (err) {
                    Login.showToast(err, 'error');
                });
            }
        });
        // 切换用户名或密码登录
        $('#userNameOrPhone').click(function () {
            if ($(this).attr('type') === 'phone') {
                $(this).attr('type', 'userName');
                $(this).text('手机号密码登录');
                $('#passwordLoginPhoneInput').attr('placeholder', '请输入用户名');
                $('#passwordLoginPhoneInput').attr('maxlength', 30);
            } else if ($(this).attr('type') === 'userName') {
                $(this).attr('type', 'phone');
                $(this).text('用户名密码登录');
                $('#passwordLoginPhoneInput').attr('placeholder', '请输入手机号');
                $('#passwordLoginPhoneInput').attr('maxlength', 11);
            }
        });
        // 验证码登录按钮点击
        $('#codeLoginBtn').click(function () {
            if (Login.phoneVerify('#codeLoginPhoneInput') &&
                Login.nullValueVerify('#codeLoginCodeInput')) {
                LoginAjax.loginByPhoneCode($('#codeLoginPhoneInput').val(), $('#codeLoginCodeInput').val(), '', function (res) {
                    Login.showToast('登录成功', 'success');
                }, function (err) {
                    console.log(err);
                    Login.showToast(err, 'error');
                });
            }
        });
        // 密码登录按钮点击
        $('#passwordLoginBtn').click(function () {
            if ($('#userNameOrPhone').attr('type') === 'phone') {
                if (Login.phoneVerify('#passwordLoginPhoneInput') &&
                    Login.nullValueVerify('#passwordLoginPasswordInput')) {
                    LoginAjax.loginByPhonePassWord($('#passwordLoginPhoneInput').val(), $('#passwordLoginPasswordInput').val(), function (res) {
                        Login.showToast('登录成功', 'success');
                    }, function (err) {
                        Login.showToast(err, 'error');
                    });
                }
            } else if ($('#userNameOrPhone').attr('type') === 'userName') {
                if (Login.nullValueVerify('#passwordLoginPhoneInput') &&
                    Login.nullValueVerify('#passwordLoginPasswordInput')) {
                    LoginAjax.loginByUserNamePassword($('#passwordLoginPhoneInput').val(), $('#passwordLoginPasswordInput').val(), function (res) {
                        Login.showToast('登录成功', 'success');
                    }, function (err) {
                        Login.showToast(err, 'error');
                    });
                }
            }
        });
        // 忘记密码按钮点击
        $('#showForgetPasswordBtn').click(function () {
            Login.showView('.forgetPassword');
        });
        // 注册账号按钮点击
        $('.showRegisterBtn').click(function () {
            Login.showView('.registerAccount');
        });
        // 注册微信登录回调
        window.addEventListener(
            'message',
            function (event) {
                console.log('message received:  ' + event.data, event);
                try {
                    const loginRes = JSON.parse(event.data);
                    if (loginRes.code != 0) {
                        Login.showToast('登录失败', 'error');
                    } else {
                        LoginAjax.loginByWX(loginRes.data.code, loginRes.data.state, function (res) {
                            console.log(res);
                        }, function (err) {
                            Login.showToast(err, 'error');
                        });
                    }
                } catch (e) {
                    // console.log(e);
                }
            },
            false
        );
        // 注册账号按钮点击
        $('.wxIcon').click(function () {
            LoginAjax.getWXAppid(function (res) {
                Login.showView('.wxCode');
                new window.WxLogin({
                    self_redirect: true,
                    id: 'wxLoginCode',
                    appid: res.appid,
                    scope: 'snsapi_login',
                    redirect_uri: encodeURIComponent(
                        loginUrl.partsUrl + '/weixinLogin.html'
                    ),
                    state: res.state,
                    style: '',
                    href: 'data:text/css;base64,Ci5pbXBvd2VyQm94IC5pbmZvIHsKICAgIHdpZHRoOiAzMjBweDsKfQoKLnN0YXR1c19pY29uIHsKICAgIGRpc3BsYXk6IG5vbmUKfQoKLmltcG93ZXJCb3ggLnN0YXR1cyB7CiAgICB0ZXh0LWFsaWduOiBjZW50ZXI7Cn0KCi5pbXBvd2VyQm94IC5xcmNvZGUgewogICAgbWFyZ2luLXRvcDogMDsKICAgIHdpZHRoOiAyMjBweDsKICAgIGJvcmRlcjogMDsKfQoKLmltcG93ZXJCb3ggLnRpdGxlIHsKICAgIGRpc3BsYXk6IG5vbmU7Cn0KCi53cnBfY29kZSB7CiAgICB3aWR0aDogMzIwcHg7CiAgICB0ZXh0LWFsaWduOiBjZW50ZXI7Cn0='
                });
            }, function (err) {
                Login.showToast(err, 'error');
            });
        });
    },
    // 初始化注册视图
    initRegister: function () {
        // 勾选或取消勾选用户协议
        $('#changeAgreementStatus').click(function () {
            if ($('.acceptUserAgreement').attr('status') === 'unselect') {
                $('.acceptUserAgreement').attr('status', 'selected');
                $('.acceptUserAgreement').removeClass('aUAUnselected');
                $('.acceptUserAgreement').addClass('aUASelected');
            } else if ($('.acceptUserAgreement').attr('status') === 'selected') {
                $('.acceptUserAgreement').attr('status', 'unselect');
                $('.acceptUserAgreement').removeClass('aUASelected');
                $('.acceptUserAgreement').addClass('aUAUnselected');
            }
        });
        // 显示用户协议
        $('#showUserAgreementBtn').click(function () {
            $('#agreementTitle').text('用户协议');
            Login.showView('.agreement');
            $('#userAgreement').show();
            $('#privacyAgreement').hide();
        });
        // 显示隐私政策
        $('#showPrivacyAgreementBtn').click(function () {
            $('#agreementTitle').text('隐私政策');
            Login.showView('.agreement');
            $('#userAgreement').hide();
            $('#privacyAgreement').show();
        });
        // 注册按钮点击
        $('#registerBtn').click(function () {
            if ($('.acceptUserAgreement').attr('status') == 'unselect') {
                Login.showToast('请同意用户协议');
                return;
            }
            console.log('2');
            if (Login.phoneVerify('#registerPhoneInput') &&
                Login.nullValueVerify('#registerCodeInput')) {
                LoginAjax.loginByPhoneCode($('#registerPhoneInput').val(), $('#registerCodeInput').val(), '', function (res) {
                    Login.showToast('登录成功', 'success');
                }, function (err) {
                    Login.showToast(err, 'error');
                });
            }
        });
    },
    // 初始化忘记密码视图
    initForgetPassword: function () {
        $('#forgetPasswordNextBtn').click(function () {
            if (Login.phoneVerify('#forgetPasswordPhoneInput') &&
                Login.nullValueVerify('#forgetPasswordCodeInput')) {
                LoginAjax.verifyPhoneCode($('#forgetPasswordPhoneInput').val(), $('#forgetPasswordCodeInput').val(), function () {
                    Login.showView('.resetPassword');
                }, function (err) {
                    Login.showToast(err, 'error');
                });
            }
        });
    },
    // 初始化重置密码视图
    initResetPassword: function () {
        $('#savePasswordBtn').click(function () {
            var passwordOne = $('#resetPasswordInputOne').val();
            var passwordTwo = $('#resetPasswordInputTwo').val();
            if (passwordOne < 8 || passwordTwo < 8) {
                Login.showToast('请输入8-30位密码');
                return;
            }
            if (!(/^[a-zA-Z0-9]{1,}$/g).test(passwordOne) | !(/^[a-zA-Z0-9]{1,}$/g).test(passwordTwo)) {
                Login.showToast('密码只能包含数字和字母');
                return;
            }
            if (passwordOne !== passwordTwo) {
                Login.showToast('两次密码输入不一致');
                return;
            }
            LoginAjax.resetPassword($('#forgetPasswordPhoneInput').val(), passwordOne, function () {
                Login.showToast('修改密码成功', 'success');
                Login.clearView();
            }, function (err) {
                Login.showToast(err, 'error');
            });
        });
    },
    // 初始化绑定手机号视图
    initBindPhone: function () {
        $('#bindPhoneBtn').click(function () {
            if (Login.phoneVerify('#bindPhonePhoneInput') &&
                Login.nullValueVerify('#bindPhoneCodeInput')) {
                if ($('#bindPhoneSendVerifyCodeBtn').attr('source') == 2) {
                    LoginAjax.wxBindPhone($('#bindPhoneSendVerifyCodeBtn').attr('code'), $('#bindPhonePhoneInput').val(), $('#bindPhoneCodeInput').val(), function () {
                        console.log('绑定成功并已登录');
                    }, function (err) {
                        Login.showToast(err, 'error');
                    });
                }
                if ($('#bindPhoneSendVerifyCodeBtn').attr('source') == 4) {
                    LoginAjax.usernameBindPhone($('#bindPhoneSendVerifyCodeBtn').attr('token'), $('#bindPhonePhoneInput').val(), $('#bindPhoneCodeInput').val(), function () {
                        console.log('绑定成功并已登录');
                    }, function (err) {
                        Login.showToast(err, 'error');
                    });
                }
            }
        });
    },
    // 初始化手动发送短信视图
    initManualSendCode: function () {
        $('#msdClose').click(function () {
            $('.manualSendCode').hide();
            // Login.clearView();
        });
        $('#msdEntry').click(function () {
            LoginAjax.verifySendPhoneMessage($('#msgPhone').text(), function (code) {
                $('.manualSendCode').hide();
                if (Login.viewHistory[Login.viewHistory.length - 1] == '.codeAndPasswordLogin') {
                    $('#codeLoginCodeInput').val(code);
                    $('#codeLoginBtn').trigger('click');
                }
                if (Login.viewHistory[Login.viewHistory.length - 1] == '.registerAccount') {
                    $('#registerCodeInput').val(code);
                    $('.acceptUserAgreement').attr('status', 'selected');
                    $('#registerBtn').trigger('click');
                }
                if (Login.viewHistory[Login.viewHistory.length - 1] == '.forgetPassword') {
                    $('#forgetPasswordCodeInput').val(code);
                    $('#forgetPasswordNextBtn').trigger('click');
                }
                if (Login.viewHistory[Login.viewHistory.length - 1] == '.bindPhone') {
                    $('#bindPhoneCodeInput').val(code);
                    $('#bindPhoneBtn').trigger('click');
                }
            }, function (err) {
                Login.showToast(err + '，如已发送请稍后重试', 'error');
            });
        });
    },
    // 初始化图形验证码视图
    initImgVerifyCode: function () {
        $('#imgVClose').click(function () {
            $('#imgCode').attr('src', '').attr('account', '').attr('source', '');
            $('.imgVerifyCode').hide();
        });
        $('#imgCode').click(function () {
            $(this).attr('src', loginUrl.userUrl + '/pcuserv3_verifyCode.action' + '?member.username=' + $(this).attr('account') + '&member.source=' + $(this).attr('source') + '&tempid=' + Math.random());
        });
        $('#imgVEntry').click(function () {
            if (Login.nullValueVerify('#imgVerifyCodeInput')) {
                LoginAjax.verifyImgCode($('#imgCode').attr('account'), $('#imgVerifyCodeInput').val(), $('#imgCode').attr('source'), function (res) {
                    $('#imgVClose').trigger('click');
                    $('#passwordLoginBtn').trigger('click');
                }, function (err) {
                    $('#imgVerifyCodeInput').val('');
                    $('#imgCode').attr('src', loginUrl.userUrl + '/pcuserv3_verifyCode.action' + '?member.username=' + $('#imgCode').attr('account') + '&member.source=' + $('#imgCode').attr('source') + '&tempid=' + Math.random());
                    Login.showToast(err, 'error');
                });
            }
        });
    },
    // 显示手动发送短信视图
    showManualSendCode: function (targetPhone, code) {
        $('.manualSendCode').show();
        $('#msgCode').text(code);
        $('#msgTargetPhone').text(targetPhone);
        if (Login.viewHistory[Login.viewHistory.length - 1] == '.codeAndPasswordLogin') {
            $('#msgPhone').text($('#codeLoginPhoneInput').val());
        }
        if (Login.viewHistory[Login.viewHistory.length - 1] == '.registerAccount') {
            $('#msgPhone').text($('#registerPhoneInput').val());
        }
        if (Login.viewHistory[Login.viewHistory.length - 1] == '.forgetPassword') {
            $('#msgPhone').text($('#forgetPasswordPhoneInput').val());
        }
        if (Login.viewHistory[Login.viewHistory.length - 1] == '.bindPhone') {
            $('#msgPhone').text($('#bindPhonePhoneInput').val());
        }
    },
    // 显示绑定手机号视图
    // 0:注册短信,1:手机号登录短信,2:微信登录绑定手机号短信,3:找回密码短信,4:用户名密码登录绑定手机号短信
    showBindPhoneView: function (token, code, source) {
        Login.showView('.bindPhone');
        $('#bindPhoneSendVerifyCodeBtn').attr('token', token).attr('code', code).attr('source', source);
    },
    // 获取验证码倒计时
    countDown: function () {
        Login.verifyAwaitTime = 60;
        $('.getVerifyCode').addClass('disabled').text(Login.verifyAwaitTime + ' 秒后重发');
        Login.countDownInterval = setInterval(function () {
            Login.verifyAwaitTime -= 1;
            $('.getVerifyCode').text(Login.verifyAwaitTime + ' 秒后重发');
            if (Login.verifyAwaitTime <= 0) {
                Login.clearCountDown();
            }
        }, 1000);
    },
    // 清除验证码倒计时定时器
    clearCountDown: function () {
        clearInterval(Login.countDownInterval);
        Login.verifyAwaitTime = 0;
        $('.getVerifyCode').removeClass('disabled').text('获取验证码');
    },
    // 输入框标红
    nullValueVerify: function (selector) {
        if (!$(selector).val()) {
            $(selector).addClass('inputError');
            return false;
        }
        return true;
    },
    // 手机号验证
    phoneVerify: function (selector) {
        if (!Login.nullValueVerify(selector)) {
            return false;
        }
        if (!(/^[1][3456789][0-9]{9}$/).test($(selector).val())) {
            Login.showToast('请输入正确的手机号');
            return false;
        }
        return true;
    },
    //消息提示  type default|success|error
    showToast: function (msg, type) {
        switch (type | 'default') {
            case 'default':
                $('.toastContent').css('color', 'rgba(72, 85, 102, 1)');
                break;
            case 'success':
                $('.toastContent').css('color', '#33B071');
                break;
            case 'error':
                $('.toastContent').css('color', 'rgba(255, 77, 79, 1)');
                break;
        }
        $('.toastContent').text(msg || '');
        $('.toast').fadeIn(250);
        setTimeout(function () {
            $('.toast').fadeOut(250);
        }, 2000);
    }
};
